import axios from "axios";

const azureClientId = "8fa3387e-4122-4fe9-850b-e2df4b6fd366";
const azureOAuthRoute = "oauth/azure"
const azureScope = "Files.ReadWrite.All Files.ReadWrite.AppFolder offline_access";
const baseUrl = "https://graph.microsoft.com"
const apiBaseUrl = `${baseUrl}/v1.0/drive/special`
const azureSSOUrl = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize`
const azureGetRootFolderUrl = `${apiBaseUrl}/approot/children`;
/**
 * 文件链接
 */
const azureFileUrl = (filePath: string): string => {
    return  `${apiBaseUrl}/approot:${filePath}`;
}
/**
 * 文件元数据链接
 * @param filePath
 */
const azureFileDataMetaUrl = (filePath: string): any => {
    return azureFileUrl(filePath);
}
/**
 * 文件下载链接
 * @param filePath
 */
const azureFileDownloadUploadUrl = (filePath: string): any => {
    return `${azureFileUrl(filePath)}:/content`;
}


interface AzureFileInfo {
    createdDateTime: string;
    cTag?: string;
    deleted?: boolean;
    eTag: string;
    id: string;
    name: string;
    size: number;
    WebUrl: string;
}


/**
 * 生成登录链接
 * @param redirectUri
 * @param refreshToken
 */
function createAzureLoginURL(redirectUri: string, refreshToken?: string) {
    // console.log("redirectUri", redirectUri);
    const requestBody = new URLSearchParams();
    if (!refreshToken) {
        requestBody.append('response_mode', "fragment");
    }
    else {
        requestBody.append('refresh_token', refreshToken);
        requestBody.append('grant_type', 'refresh_token');
        requestBody.append('prompt', 'none');
        requestBody.append('nonce', '678910');
    }
    requestBody.append('response_type', "token");
    requestBody.append('scope', azureScope);
    requestBody.append('client_id', azureClientId);
    requestBody.append('redirect_uri', redirectUri);
    // console.log("url", `${azureSSOUrl}?${requestBody.toString()}`);
    return `${azureSSOUrl}?${requestBody.toString()}`;
}


/**
 * 获取项目根文件夹列表
 * @param accessToken
 */
function getAzureRootFolderUrl(accessToken: string) {
    // console.log("getAzureRootFolderUrl accessToken", accessToken);
    return new Promise((resolve, reject) => {
        axios.get(azureGetRootFolderUrl, {
            headers: {
                Authorization: `Bearer ${accessToken}`
            }
        })
            .then(response => {
                console.log("getRootFolderUrl response.data", response.data);
                resolve(response.data);
            })
            .catch(error => {
                console.error('getRootFolderUrl Error fetching files:', error);
                reject();
            });
    })
}


/**
 * 根据文件路径获取文件信息
 * @param filePath
 * @param accessToken
 */
async function getAzureFileInfoByPath(filePath: string, accessToken: string): Promise<AzureFileInfo | any> {
    return new Promise((resolve, reject) => {
        axios.get(azureFileDataMetaUrl(filePath), {
            headers: {
                Authorization: `Bearer ${accessToken}`
            }
        })
            .then(response => {
                console.log("getAzureFileInfoByPath response.data", response.data);
                resolve(response.data);
            })
            .catch(error => {
                if (error.status === 404) {
                    resolve(null);
                }
                // console.error('getAzureFileInfoByPath Error fetching files:', error);
                reject(error);
            });
    })
}


/**
 * 根据文件路径下载文件
 * @param filePath
 * @param accessToken
 */
async function downloadAzureFileByPath(filePath: string, accessToken: string): Promise<any> {
    return new Promise((resolve, reject) => {
        axios.get(azureFileDownloadUploadUrl(filePath), {
            headers: {
                Authorization: `Bearer ${accessToken}`
            }
        })
            .then(response => {
                // console.log("getAzureFileInfoByPath response", response);
                resolve(response.data);
            })
            .catch(error => {
                if (error.status === 404) {
                    resolve(null);
                }
                // console.error('getAzureFileInfoByPath Error fetching files:', error);
                reject(error);
            });
    })
}


/**
 * 上传文件到文件路径
 * @param file
 * @param filePath
 * @param accessToken
 */
async function uploadAzureFile(file: any, filePath: string, accessToken: string): Promise<any> {
    // const formData = new FormData();
    // formData.append('file', file);
    return new Promise((resolve, reject) => {
        axios.put(azureFileDownloadUploadUrl(filePath), file, {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
        })
            .then(response => {
                // console.log("上传文件到文件路径 response", response);
                resolve(response.data);
            })
            .catch(error => {
                // console.log("上传文件到文件路径出错 error", error);
                reject(error);
            });
    })
}


function parseAzureLoginResponse(response: string) {
    const url = new URL(response);
    const fragment = url.hash.slice(1); // 去掉#符号
    const fragmentParams = new URLSearchParams(fragment);
    return fragmentParams.get("access_token");
}



export {
    azureClientId,
    azureOAuthRoute,
    azureSSOUrl,
    azureScope,
    AzureFileInfo,
    parseAzureLoginResponse,
    createAzureLoginURL,
    getAzureRootFolderUrl,
    getAzureFileInfoByPath,
    downloadAzureFileByPath,
    uploadAzureFile,
};
